<?php 
//设置cookie
//setcookie("pgv_pvi", "Alex Porter", time()+3600);
//TODO:之后考虑cookie过期问题 和 固定串领饼干问题


function getRealUserId($ckuser){
	$stSalt = 4;
	return substr(base64_decode($ckuser),$stSalt);	
}
function createCookie($s){
	$salt = createRandomStr(4);
	return base64_encode($salt.$s);
}
function createRandomStr($length){
	$arr = "";
	for($i=0;$i<$length;++$i){
		$tp = mt_rand(0,61);
		if($tp < 10)$tp = chr($tp+ord('0'));
		else if($tp > 35)$tp = chr($tp-36+ord('a'));
		else $tp = chr($tp-10+ord('A'));
		$arr = $arr.$tp;
	}	
	return $arr;
}
$findflag = false;
$cookieLastTime = 360000;
include 'forum/opDB.php';

if (isset($_COOKIE['pgv_pvi'])){
	$ckuser = $_COOKIE['pgv_pvi'];
	//echo $ckuser;
	$realUserId = getRealUserId($ckuser);

	if($realUserId != false){
		$user_sql = 'SELECT * FROM `user` WHERE `realUserId` = \''.$realUserId.'\' LIMIT 0, 1 ';
		$result = mysql_query($user_sql);	
		if($result != false){
			$row = mysql_fetch_array($result);
			$userid_post = $row['userId'];//发串回串用的ID
			setcookie("pgv_pvi",$ckuser, time()+$cookieLastTime);
			$findflag = true;
		}
	}
}

if($findflag == false){
	//TODO:目前先开放1000个cookie
	$cktotalnum = mysql_num_rows(mysql_query('SELECT `userId` FROM `user`'));
	if($cktotalnum > 1000){
		return ;	
	}
	
	while(true){//制作不重复的realUserId
		$newRealUserId = createRandomStr(16);
		$user_sql = 'SELECT * FROM `user` WHERE `realUserId` LIKE \''.$newRealUserId.'\' LIMIT 0, 1 ';
		$result = mysql_query(mysql_escape_string($user_sql));	
		if(!$result|| !mysql_fetch_array($result))break;

	}

	while(true){
		$newUserId = createRandomStr(8);
//		echo $newUserId;
		$user_sql = 'SELECT * FROM `user` WHERE `userId` = \''.$newUserId.'\' LIMIT 0, 1 ';
		$result = mysql_query(mysql_escape_string($user_sql));	
		if(!$result || !mysql_fetch_array($result))break;

	}
	
	$user_sql = 'INSERT INTO `nmb`.`user` (`userId`, `realUserId`, `lastLogin`, `level`) VALUES (\''.$newUserId.'\', \''.$newRealUserId.'\', CURRENT_TIMESTAMP, \'0\')';
	mysql_query($user_sql);
	$newcookie = createCookie($newRealUserId);
	setcookie("pgv_pvi",$newcookie,time()+$cookieLastTime);
	$userid_post = $newUserId;
}
//echo $newcookie;
//echo '<p>'.$newRealUserId.'</p>';

mysql_close($con);
?>
